<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
    <script type="text/javascript" src="js/json2.js"></script>
    <script type="text/javascript">
        function method01(){
            //获取网页中需要传送的数据
            var usernamevalue=document.getElementById('username').value;
            var userpasswordvalue=document.getElementById('userpassword').value;
            //把数据封装到js对象里
            var jsObject=new Object();
            jsObject.name=usernamevalue;
            jsObject.password=userpasswordvalue;
            //把js对象转换成json格式字符串
            var jsonString=JSON.stringify(jsObject);
            console.log('传送的json格式字符串为：'+jsonString+'。');
            var xhr=new XMLHttpRequest();
            xhr.open('POST','${pageContext.request.contextPath}/servlet/servlet01');
            //告诉服务器端  数据的组织方式是json
            xhr.setRequestHeader('Content-Type','application/json');
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        //返回的是json格式字符串
                        var backContent=xhr.responseText;
                        console.log('后台返回的内容为：'+backContent+'。');
                        //把json格式字符串转换成json对象
                        var jsonObjectBack=eval('('+backContent+')');
                        var usernamespan=document.getElementById('usernameback');
                        var userpasswordspan=document.getElementById('userpasswordback');
                        usernamespan.innerHTML=jsonObjectBack.name;
                        userpasswordspan.innerHTML=jsonObjectBack.password;
                    }
                }
            }
            xhr.send(jsonString);
        }
    </script>
</head>
<body>
用户名：<input type="text" id="username"><br>
密&nbsp;&nbsp;&nbsp;码：<input type="password" id="userpassword"><br>
<input type="button" value="提交" onclick="method01()">
<input type="button" value="重置">
<hr>
返回的数据：
<br>
用户名：<span id="usernameback"></span>
<br>
密码：<span id="userpasswordback"></span>
</body>
</html>